package com.daxia.ogmall.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daxia.ogmall.common.AdType;
import com.daxia.ogmall.dao.AdDAO;
import com.daxia.ogmall.dto.AdDTO;
import com.daxia.ogmall.model.Ad;
import com.daxia.ogmall.support.Page;
import com.daxia.ogmall.util.BeanMapper;

@Service
public class AdService {
	
	@Autowired
	private AdDAO adDAO;
	
	public List<AdDTO> find(AdDTO query, Page page) {
		List<Ad> models = adDAO.find(query, page);
		List<AdDTO> dtos = toDTOs(models);
		return dtos;
	}
	
	public List<AdDTO> findAll() {
		return this.find(new AdDTO(), null);
	}
	
	public List<AdDTO> find(int count) {
		Page page = new Page();
		page.setPage(1);
		page.setPageSize(count);
		return this.find(new AdDTO(), page);
	}
	
	public Long create(AdDTO dto) {
		Ad model = new Ad();
		toModel(model, dto);
		return adDAO.create(model);
	}
	
	public AdDTO load(Long id) {
	    Ad model = adDAO.load(id);
	    return toDTO(model);
    }

	public void updateAllFields(AdDTO dto) {
		Ad model = adDAO.load(dto.getId());
		toModel(model, dto);
		adDAO.update(model);
    }

	public void deleteByIds(Long[] ids) {
		if (ids != null) {
			for (Long id : ids) {
				// adDAO.deleteById(id);
				adDAO.deleteByIdPhysical(id);
			}
		}
    }
	
	public void deleteById(Long id) {
		this.deleteByIds(new Long[] {id});
	}

	public AdDTO findOne(AdDTO query) {
		Ad model = adDAO.findOne(query);
		return toDTO(model);
	}
	
	private List<AdDTO> toDTOs(List<Ad> models) {
		if (CollectionUtils.isEmpty(models)) {
			return new ArrayList<AdDTO>(0);
		}
		List<AdDTO> dtos = new ArrayList<AdDTO>(models.size());
		for (Ad model : models) {
	        AdDTO dto = toDTO(model);
	        dtos.add(dto);
        }
	    return dtos;
    }
    
    private AdDTO toDTO(Ad model) {
		if (model == null) {
			return null;
		}
		AdDTO dto = BeanMapper.map(model, AdDTO.class);
		
		return dto;
	}
	
	private void toModel(Ad model, AdDTO dto) {
		BeanMapper.copy(dto, model);
    }
	
	@SuppressWarnings("unused")
	private List<Ad> toModels(List<AdDTO> dtos) {
		if (CollectionUtils.isEmpty(dtos)) {
			return new ArrayList<Ad>(0);
		}
		List<Ad> models = new ArrayList<Ad>(dtos.size());
		for (AdDTO dto : dtos) {
	        Ad model = new Ad();
	        toModel(model, dto);
	        models.add(model);
        }
		return models;
	}

	public List<AdDTO> findByType(AdType type) {
		AdDTO q = new AdDTO();
		q.setType(type.getValue());
		return this.find(q, null);
	}
}
